import { defineStore } from "pinia";
import { getDepKey, clearDepKey, clearDepName, setDepName, clearToken } from "../utils/index";

export interface UserStoreInterface {
  user: any;
  departments: any[];
  currentDepId: number;
  resourceUrl: ResourceUrlModel;
  isLogin: boolean;
}

const defaultValue: UserStoreInterface = {
  user: null,
  departments: [],
  currentDepId: Number(getDepKey()) || 0,
  resourceUrl: {},
  isLogin: false,
};

export const useUserStore = defineStore("user", {
  state: () => defaultValue,

  actions: {
    loginAction(payload: any) {
      this.user = payload.user;
      this.departments = payload.departments;
      this.resourceUrl = payload.resource_url;
      this.isLogin = true;
      if (payload.departments.length > 0 && !getDepKey()) {
        this.currentDepId = payload.departments[0].id;
        setDepName(payload.departments[0].name);
      }
    },

    logoutAction() {
      this.user = null;
      this.departments = [];
      this.isLogin = false;
      this.currentDepId = 0;
      this.resourceUrl = {};
      clearToken();
      clearDepKey();
      clearDepName();
    },

    saveCurrentDepId(depId: number) {
      this.currentDepId = depId;
    },
  },
});
